package com.vic.kjlink.order.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.vic.kjlink.order.model.Start;
import com.vic.kjlink.order.model.User;
import com.vic.kjlink.order.service.IndexService;
import com.vic.kjlink.order.service.StartService;

import pers.vic.boot.base.model.BaseResponse;
import pers.vic.boot.base.model.Remind;
import pers.vic.boot.util.CookieUtil;

/**
 * @author Vic.xu
 * @date 2021/08/18
 */
@Controller
public class IndexController extends BaseOrderController {

    @Resource
    private IndexService indexService;

    @Resource
    private StartService startService;

    @GetMapping(value = {"", "/"})
    public String root() {
        return "redirect:login";
    }

    /**
     * 首页
     * 
     * @return
     */
    @GetMapping(value = "index")
    public String index(Model model) {
        Start lastOpen = startService.getLastOpen();
        if (lastOpen == null || lastOpen.getId() == null) {
            model.addAttribute("starting", false);

        } else {
            model.addAttribute("starting", true);
        }
        return "index";
    }

    /**
     * 前往登录页面
     * 
     * @return
     */
    @GetMapping(value = "/login")
    public String toLogin() {
        User user = indexService.ifLogin(request);
        if (user != null) {
            return "redirect:/index";
        }
        return "login";
    }

    /**
     * 登录
     * 
     * @param userCode
     *            userCode
     * @param password
     *            password
     * @param rememberMe
     *            remomber me
     * @param attributes
     *            none
     * @return
     */
    @PostMapping(value = "/login")
    public String login(String userCode, String password, @RequestParam(required = false) boolean rememberMe,
        RedirectAttributes attributes) {
        BaseResponse<User> response = indexService.login(userCode, password);
        if (response.getCode() != 0) {
            attributes.addFlashAttribute(Remind.warning().setMessage(response.getMsg()));
            return "redirect:login";
        }
        User user = response.getData();
        storeUser(user);
        String userToken = indexService.makeToken(user);
        if (rememberMe) {
            CookieUtil.set(this.response, PRINCIPAL, userToken, rememberMe);
        }
        attributes.addFlashAttribute(Remind.success());
        return "redirect:index";
    }

    /**
     * 退出
     * 
     * @return
     */
    @GetMapping(value = "logout")
    public String logout() {
        cleanSession();
        CookieUtil.remove(request, response, PRINCIPAL);
        return "redirect:login";
    }

}
